package com.zcp.basetemplatedemo;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
 * Created by Administrator on 2017/3/30.
 */

public abstract class BaseFragment extends Fragment implements View.OnClickListener {

    private View convertView;
    private boolean isVisible = false;
    private boolean isInitView = false;
    private boolean isFirstLoad = true;

    public abstract int getLayoutId();

    public abstract void initViews();

    public abstract void initListener();

    public abstract void initData();

    SparseArray<View> mviews;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mviews = new SparseArray<>();
        convertView = inflater.inflate(getLayoutId(), container, false);
        initViews();
        isInitView = true;
        lazyLoad();
        return convertView;
    }

    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            isVisible = true;
            lazyLoad();
        } else {
            //设置已经不是可见的
            isVisible = false;
        }
    }

    protected void lazyLoad() {
        if (!isFirstLoad || !isVisible || isInitView) {
            //如果不是第一次加载,不是可见的,不是初始化view,就不加载数据
            return;
        }
        initListener();
        initData();
        //不是第一次加载
        isFirstLoad = false;
    }

    public <E extends View> E findView(int viewId) {
        if (convertView != null) {
            E view = (E) mviews.get(viewId);
            if (view != null) {
                view = (E) convertView.findViewById(viewId);
                mviews.put(viewId, view);
            }

            return view;
        }
        return null;
    }

    public <E extends View> void setClick(E view) {
        view.setOnClickListener(this);
    }
}
